package com.bbs.controller;

import com.bbs.dto.DialogDto;
import com.bbs.dto.SendUserMessageRequest;
import com.bbs.pojo.Result;
import com.bbs.pojo.UserPrincipal;
import com.bbs.pojo.dto.MessageDto;
import com.bbs.service.ChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/api")
public class ChatController {
    @Autowired
    ChatService chatService;

    /**
     * 向用户发送私聊消息
     * @param user
     * @param sendUserMessageRequest
     * @return
     */
    @PostMapping("/chats")
    @PreAuthorize("isAuthenticated()")
    public Result<Object> sendUserMessage(@AuthenticationPrincipal UserPrincipal user, @RequestBody SendUserMessageRequest sendUserMessageRequest){
        String senderId = user.getUserId();
        String receiverId = sendUserMessageRequest.getReceiverId();
        String content = sendUserMessageRequest.getContent();
        return Result.build(chatService.sendUserMessage(senderId, receiverId, content));
    }

    /**
     * 获取某个时刻之后的对话列表，并确认消息
     * @param user
     * @param receiverId
     * @param time
     * @return
     */
    @GetMapping("/chats/{receiverId}")
    @PreAuthorize("isAuthenticated()")
    public Result<List<DialogDto>> getDialogsAfter(@AuthenticationPrincipal UserPrincipal user,
                                                   @PathVariable("receiverId") String receiverId,
                                                   @RequestParam(value = "after", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime time){
        if(time == null){
            return Result.withData(chatService.getDialogs(user.getUserId(), receiverId));
        }else{
            return Result.withData(chatService.getDialogsAfter(user.getUserId(), receiverId, time));
        }
    }

    @GetMapping("/chats/news")
    @PreAuthorize("isAuthenticated()")
    public Result<List<MessageDto>> getLastUserMessageGroupBySender(@AuthenticationPrincipal UserPrincipal user){
        return Result.withData(chatService.getLastUserMessageGroupBySender(user.getUserId()));
    }

    /**
     * 获取有消息但未确认的用户的id的列表
     * @return
     */
    @GetMapping("/chats/acknowledged-users")
    @PreAuthorize("isAuthenticated()")
    public Result<List<String>> getAcknowledgedUsers(@AuthenticationPrincipal UserPrincipal user){
        return Result.withData(chatService.getAcknowledgedUsers(user.getUserId()));
    }
}
